﻿using System;

using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace MSL.Tool
{
    /// <summary>
    /// 托盘图标辅助类
    /// </summary>
    public class NotifyIconHelper
    {
        #region 字段

        /// <summary>
        /// 状态枚举：离线、在线、闪烁
        /// </summary>
        public enum Status
        {
            OffLine,
            OnLine,
            TwinkleNotice
        }

        private Status status;
        private NotifyIcon notifyIcon;
        private Timer timer;
        private bool isBlank = false;//是否后台运行
        #endregion

        #region 属性
        /// <summary>
        /// 未连接图标 如:网络断开
        /// </summary>
        public Icon UnConntectIcon { get; set; }

        /// <summary>
        /// 已连接 
        /// </summary>
        public Icon ConntectedIcon { get; set; }

        /// <summary>
        /// 未连接上的托盘文本提示
        /// </summary>
        public string UnConntectText { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string ConntectedText { get; set; }

        /// <summary>
        /// 闪烁图标1
        /// </summary>
        public Icon ShrinkIcon1 { get; set; }

        /// <summary>
        /// 闪烁图标2
        /// </summary>
        public Icon ShrinkIcon2 { get; set; }

        /// <summary>
        /// 托盘的状态
        /// </summary>
        public Status NotifyStatus
        {
            get { return this.status; }
            set
            {
                if (value == this.status) return;

                if (status == Status.TwinkleNotice && timer != null)
                {
                    timer.Stop();
                }
                this.status = value;
                Refresh();
            }
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="notify"></param>
        public NotifyIconHelper(NotifyIcon notify)
        {
            this.notifyIcon = notify;
            this.NotifyStatus = Status.OffLine;
            this.timer = new Timer();
            this.timer.Interval = 500;
            this.timer.Tick += new EventHandler(timer_Tick);
        }

        /// <summary>
        /// 刷新托盘图标的状态
        /// </summary>
        public void Refresh()
        {
            switch (status)
            {
                case Status.OffLine:
                    notifyIcon.Icon = UnConntectIcon;
                    notifyIcon.Text = UnConntectText;
                    break;

                case Status.OnLine:
                    notifyIcon.Icon = ConntectedIcon;
                    notifyIcon.Text = ConntectedText;
                    break;

                case Status.TwinkleNotice:
                    timer.Start();
                    break;
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            notifyIcon.Icon = isBlank ? ShrinkIcon1 : ShrinkIcon2;
            isBlank = !isBlank;
        }
    }
}
